package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AAentivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.PayString;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.GroupMemberAdpter;
import com.sam.im.heiqun.uis.beans.AATransDetailBean;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.TimeUtil;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.image.CircleImageView;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * AA收款
 */
public class AAActivity extends BaseSwipeBackActivity {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_discribe)
    TextView tvDiscribe;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.sure_bt)
    Button sureBt;
    @BindView(R.id.relative_title)
    RelativeLayout relative_title ;
    @BindView(R.id.aa_users)
    RecyclerView aa_users ;
    @BindView(R.id.txt_num)
    TextView txt_num ;
    ImMessage imMessage =null ;
    private int tag;
    private AlertDialog payDialog;
    PasswordEditText payPSD;
    private String amt;
    private String transId;
    private boolean payed;
    private static final String TAG = "AAActivity";
    public static final int REQUST_SENDTOFRIEND = 111;//发送消息给好友

    private GroupMemberAdpter mGroupMemberAdpter;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_aa;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.title_aa);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor(R.color.title_aa));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        relative_title.setBackgroundColor(getResources().getColor(R.color.title_aa));
        imMessage = (ImMessage) getIntent().getSerializableExtra("data");
        Log.i(TAG, "initViews: ----" + imMessage.toString());
        tag = getIntent().getIntExtra("tag",0);
        String fromname = imMessage.getFromname();
        String imageIconUrl = imMessage.getImageIconUrl();
        String content = imMessage.getContent();
        Glide.with(this).load(imageIconUrl).centerCrop().into(imgIcon);

        tvName.setText(fromname+getResources().getString(R.string.send_aa_ed));
        Long receiveTime = imMessage.getReceiveTime();
        String mdTime = TimeUtil.getMDTime(receiveTime);
        tvTime.setText(mdTime);
        payed = imMessage.isPayed();

        aa_users.setLayoutManager(new LinearLayoutManager(this, OrientationHelper.HORIZONTAL, false));
        mGroupMemberAdpter = new GroupMemberAdpter(this, 1);
        mGroupMemberAdpter.setItemClickListener(new GroupMemberAdpter.GroupMemberListClickListener() {
            @Override
            public void onGroupMemberListClick(View view, int position) {

            }
        });
        aa_users.setAdapter(mGroupMemberAdpter);
        mGroupMemberAdpter.refresh(mFriendEntivities);

        try {
            AAentivity aAentivity = new Gson().fromJson(content, AAentivity.class);
            amt = aAentivity.getAmt();
            String counts = aAentivity.getCounts();
            String msg = aAentivity.getMsg();
            String totalAmt = aAentivity.getTotalAmt();
            transId = aAentivity.getTransId();
            Log.i(TAG, "initViews: ===============transId="+transId);

            tvMoney.setText(amt +getResources().getString(R.string.yuan));
            tvContent.setText(msg);
            tvDiscribe.setText(counts+getResources().getString(R.string.ren_gong)+totalAmt+getResources().getString(R.string.yuan));
            getAADetails();
        }catch (Exception e){
            e.printStackTrace();
        }
        if (tag ==1){
            sureBt.setText(getResources().getString(R.string.call_friend));
        }else if (tag ==2){
//            if (payed){
//                sureBt.setText("已支付");
//                sureBt.setEnabled(false);
//                sureBt.setBackgroundResource(R.drawable.shape_sure_bt_false);
//            }else {
//                sureBt.setText("AA支付");
//            }
        }



    }

    @OnClick({R.id.pre_v_back, R.id.sure_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.sure_bt :
                if (tag==1){
//TODO 通知好友接口，等待提供
                    Intent intent = new Intent(AAActivity.this, SelecteLocalFriendActivity.class);
                    intent.putExtra("tag", 11);
                    intent.putExtra("msg", imMessage);
                    startActivityForResult(intent, REQUST_SENDTOFRIEND);
                }else if (tag==2){
                    final UserEntivity user = ToolsUtils.getUser();
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                        showSetPSWdialog();
                        return;
                    }
                    showPayDialog();
                }
                break;
        }
    }
    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(AAActivity.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(AAActivity.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        try {
            payDialog = new AlertDialog.Builder(this).setView(dialog).create();
            payDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }

        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payDialog.dismiss();
            }
        });
        payCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    dopaymoney(pwd,imMessage.getDestid());
                    //  validatePayPwd(pwd);
                    payDialog.dismiss();
                }
            }
        });
    }

    private void popupKeyboard(final PasswordEditText editText) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    /**
     * AA收款-付款 transfer/aaTransPay
     * amount 付款金额 string @mock=0.01
     destId 收款用户id string @mock=17229
     payPwd 支付密码 string @mock=sdsadsa
     transId 转账ID string @mock=2
     userId
     *
     */
    private void dopaymoney(String psw, final long receiptId) {
        showProgress(getResources().getString(R.string.commit_now));
        String payPsd = MD5.MD532(psw);
        // Log.i("info","支付密码=="+psw);
        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        String destid1=Long.toString(receiptId);//把destid强转成string类型
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("amount", amt);
        json.put("destId", destid1);
        json.put("payPwd", payPsd);
        json.put("transId",transId);
        json.put("userId", userId);
        String content = RequestRSAUtils.setRsaContent(json);
        PGService.getInstance().aaTransPay(content).subscribe(new AbsAPICallback<ValidateEntivity>() {
       // PGService.getInstance().aaTransPay(amt, receiptId+"", payPsd, transId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {

                Log.i(TAG, "onResultError: ------ex.getCode()----"+ex.getCode());
                if (ex != null) {
//
                    if (-1 == ex.getCode()){
                        ToolsUtils.showToast(AAActivity.this, getResources().getString(R.string.pay_psw_error));
                    }
                    if (3 == ex.getCode()){
                        ToolsUtils.showToast(AAActivity.this, getResources().getString(R.string.no_money));
                    }
                }
                hideProgress();
            }
            @Override
            public void onNext(ValidateEntivity validateEntivity) {//这里支付成功后不做发送消息处理
                if (validateEntivity != null) {
                    ToolsUtils.showToast(AAActivity.this, validateEntivity.getInfo());
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("amt",amt+"");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final ImMessage immsg = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_PAYFOR, UUID.randomUUID().toString(), Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_SYS,receiptId,obj.toString(), Constant.MESSAGE_TYPR_TOPAYFOR,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, null, ToolsUtils.getMyUserId() + "___", 0, imMessage.getImageIconUrl());
                    immsg.save();
                    MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(immsg, Constant.FROM_TYPE_OTHER);
                    EventBus.getDefault().post(new PayString(imMessage.getMsgId()));
                    EventBus.getDefault().post(messageEntivity);
                    hideProgress();
                    finish();
                } else {
                    ToolsUtils.showToast(AAActivity.this, getResources().getString(R.string.pay_fail));
                }
                hideProgress();//RecordVideo
            }
        });
    }
    //生成消息对象
    public ImMessage getTbub(int version, int devType, int geoId, int type,
                             String msgId, long fromId, int fromType,
                             long destId, String content, int messageType,
                             long sendTime, long receiveTime, int status, String filePath, String uniqueness, float seconds, String imageIconUrl) {
        ImMessage tbub = new ImMessage();
        tbub.setVersion(version);
        tbub.setDevType(devType);
        tbub.setUserVoiceTime(seconds);
        tbub.setType(type);
        tbub.setGeoId(geoId);
        tbub.setMsgId(msgId);
        tbub.setFromid(fromId);
        tbub.setFromType(fromType);
        //tbub.setFileUrl(content);
        tbub.setFilePath(filePath);
        //tbub.setUserVoicePath(content);
        tbub.setDestid(destId);
        if (content.equals("null")){
            content = "null ";
        }
        tbub.setContent(content);
        tbub.setMessageType(messageType);
        tbub.setFromname(ToolsUtils.getUser().getNickName());//设置名字
        tbub.setSendTime(sendTime);
        tbub.setReceiveTime(receiveTime);
        tbub.setStatus(status);
        tbub.setUniqueness(uniqueness);
        tbub.setSendState(Constant.SENDING);
        tbub.setImageIconUrl(imageIconUrl);
        // tbub.save();
        //  ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
        //  IMMessageToJson.ImMessageToMessageEntivity(tbub, Constant.FROM_TYPE_SELF);
        return tbub;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUST_SENDTOFRIEND:
                if (resultCode == REQUST_SENDTOFRIEND) {
                    scrollToFinishActivity();
                }
                break;
        }
    }

    /**
     *
     */
    private void getAADetails() {
        showProgress(getResources().getString(R.string.now_down));
        PGService.getInstance().aaTransDetail( transId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<AATransDetailBean>() {
            @Override
            protected void onResultError(ApiException ex) {

                hideProgress();
            }
            @Override
            public void onNext(AATransDetailBean aaTransDetailBean) {//

                if (null!=aaTransDetailBean && null!=aaTransDetailBean.getRecords()){
                    if (aaTransDetailBean.getRecords().size()>0)txt_num.setText(getResources().getString(R.string.pay_ok_ed)+aaTransDetailBean.getRecords().size()+"人");
                    else txt_num.setText(getResources().getString(R.string.pay_ok_ed)+0+getResources().getString(R.string.person));
                    mFriendEntivities.addAll(aaTransDetailBean.getRecords());
                    mGroupMemberAdpter.notifyDataSetChanged();
                }
                if (null!=aaTransDetailBean && null!=aaTransDetailBean.getTransInfo()
                        && "2".equals(aaTransDetailBean.getTransInfo().getStatus())){
                    //已过期
                    sureBt.setText(getResources().getString(R.string.this_old));
                    sureBt.setEnabled(false);
                    sureBt.setBackgroundResource(R.drawable.shape_sure_bt_false);
                }else {
                    int count = 0;
                    if (null != aaTransDetailBean.getTransInfo()){
                        try {
//                            if (aaTransDetailBean.getTransInfo().getCounts())
                            count = Integer.parseInt(aaTransDetailBean.getTransInfo().getCounts());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if (null!=aaTransDetailBean && "0".equals(aaTransDetailBean.getIsPayed())){
                        //未支付，需要支付
                        if (null!= aaTransDetailBean.getRecords() && aaTransDetailBean.getRecords().size() >= count-1){
                            //已经付完
                            sureBt.setText(getResources().getString(R.string.man_pay));
                            sureBt.setEnabled(false);
                            sureBt.setBackgroundResource(R.drawable.shape_sure_bt_false);
                        }else {
                            if (tag == 1){
                                //自己
                                sureBt.setText(getResources().getString(R.string.call_friend));
                            }else {
                                sureBt.setText(getResources().getString(R.string.pay_aa));
                            }

                        }
                    }else {
                        //不需要支付
                        if (null!= aaTransDetailBean.getRecords() && aaTransDetailBean.getRecords().size() >= (count-1)){
                            //已经付完
                            sureBt.setText(getResources().getString(R.string.man_pay));
                        }else {
                            sureBt.setText(getResources().getString(R.string.pay_old));
                        }

                        sureBt.setEnabled(false);
                        sureBt.setBackgroundResource(R.drawable.shape_sure_bt_false);
                    }
                }

                hideProgress();//RecordVideo
            }
        });
    }

}
